<?php
/**
 * Created by PhpStorm.
 * User: ai
 * Date: 2017/9/18
 * Time: 15:10
 */
namespace backend\models;

use yii\base\Model;
use yii\web\UploadedFile;

class UploadForm extends Model
{
    /**
     * @var UploadedFile[]
     */

    public $uploadFile;

    public function scenarios()
    {
        return [
            'excel' => ['uploadFile'],
            'image' => ['uploadFile'],
        ];
    }

    public function rules()
    {
        return [
            [['uploadFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png,jpg,jpeg,gif', 'maxFiles' => 0, 'on' => ['image']],
            [['uploadFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'xls,xlsx,csv', 'on' => ['excel']],
        ];
    }

    /**
     * @desc 上传多个文件
     * @param string $base_path
     * @return array|bool
     */
    public function uploadMultiple($base_path = 'uploads')
    {
        $path = $base_path . '/' . date('Ymd', time()) . '/';
        if (!is_dir($path)) {
            mkdir($path, 0777, true);
        }
        if ($this->validate()) {
            $upload_results = [];
            foreach ($this->allFiles as $file) {
                $file_name = $path . uniqid(time(), false) . '.' . $file->extension;
                $upload_result['file_name'] = $file->baseName;
                $upload_result['file_save_name'] = $file_name;
                if ($file->saveAs($file_name)) {
                    $upload_result['result'] = 'success';
                } else {
                    $upload_result['result'] = $file->error;
                }
                $upload_results[] = $upload_result;
            }
            return $upload_results;
//            return true;
        } else {
            return ['error' => $this->firstErrors['allFiles']];
        }
    }

    /**
     * @desc 上传单个文件
     * @param string $base_path
     * @return array
     */
    public function uploadOne($base_path = 'uploads')
    {
        $path = $base_path . '/' . date('Ymd', time()) . '/';
        if (!is_dir($path)) {
            mkdir($path, 0777, true);
        }
        if ($this->validate()) {
            $file_name = $path . uniqid(time(), false) . '.' . $this->uploadFile->extension;
            $upload_result['file_name'] = $this->uploadFile->baseName;
            $upload_result['file_save_name'] = $file_name;
            if ($this->uploadFile->saveAs($file_name)) {
                $upload_result['result'] = 'success';
            } else {
                $upload_result['result'] = $this->uploadFile->error;
            }
            return $upload_result;

        } else {
            return ['error' => $this->firstErrors['uploadFile']];
        }
    }


}